﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

/*
1、命名空间 using System.Messaging;

2、默认存储路径 C:\WINDOWS\system32\msmq\storage

3、创建消息队列：MessageQueue mq = MessageQueue.Create(@".\Private$\LeeMSMQ");

4、删除队列：MessageQueue.Delete(@".\Private$\LeeMSMQ");

5、发送消息：MessageQueue mq = new MessageQueue(@".\Private$\LeeMSMQ");

            mq.Send("sayhello1,hello msmq!", "sayhello1");

            mq.Send("sayhello2,hello msmq!", "sayhello2");

6、接受并删除消息：MessageQueue mq = new MessageQueue(@".\Private$\LeeMSMQ")

            Message msg = mq.Receive();//引用的队列中可用的第一条消息

7、接受但不删除消息：Message msg = mq.Peek();

8、删除所有消息： Message msg = mq.Purge();

9、返回本机所有私有队列的消息

      //返回本机所有私有队列的消息

             foreach (MessageQueue mq in MessageQueue.GetPrivateQueuesByMachine("liyanping"))

            {

                mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });

                Message[] msg = mq.GetAllMessages();

                foreach (Message m in msg)

                {

                    Console.WriteLine("label:{0},body:{1}", m.Label, m.Body);

                }

            }

10、返回指定队列的消息

            if (MessageQueue.Exists(@".\Private$\LeeMSMQ"))//判断私有消息是否存在

            {

                using (MessageQueue mq = new MessageQueue(@".\Private$\LeeMSMQ"))

                {

                    mq.Formatter = new XmlMessageFormatter(new string[] { "System.String" });//设置消息队列格式化器

                    Message msg = mq.Receive();//接收消息

                    Console.WriteLine("label:{0},body: {1}", msg.Label, msg.Body);//输出消息

                    MessageQueue.Delete(@".\Private$\LeeMSMQ");

                }

            } 



    */
namespace MSMQ试用
{
    public class MSMQ读取写入
    {
        //
        System.Messaging.MessageQueue msmq = null;
        string path = @".\Private$\SkybotMQ";
        /// <summary>
        /// 创建MQ队列带消息号的
        /// </summary>
        /// <param name="qNumbwr">队列编号</param>
        public void Init(int qNumbwr = 0)
        {
            path = path + qNumbwr;
            if (System.Messaging.MessageQueue.Exists(path))
            {

                msmq = new System.Messaging.MessageQueue();
                msmq.Path = path;

            }
            else
            {
                msmq = System.Messaging.MessageQueue.Create(path);
            }

            //设置自定义序列化
            msmq.Formatter = new BytesFormatter();
            dom.NextBytes(abcdef);
            tc.dat = abcdef.Take(800).Select(p => (double)p).ToArray();

        }

        testClass tc = new testClass() { };
        Random dom = new Random();
        /// <summary>
        /// 返回消息数据
        /// </summary>
        /// <returns></returns>
        public void GetMsg()
        {
            try
            {

                var b = msmq.Receive();
                Dser((byte[])b.Body);
            }
            catch (Exception ex) { Console.WriteLine(ex); }
        }

        byte[] abcdef = new byte[1024 * 8];


        public void SendMsg()
        {

            try
            {
                tc.token = Guid.NewGuid().ToString();
                byte[] arr = Ser(tc);
                //8k ,send3次报错 ，提供资源不足无法操作
                //最多能保存93727人8KB的包
                msmq.Send(arr);
                //msmq.Send("aaa," + Guid.NewGuid() );
            }
            catch (Exception ex) { Console.WriteLine(ex); }

        }

        double[] cc = new double[800];

        testClass Dser(byte[] arr)
        {
            testClass result;
            using (var ms = new System.IO.MemoryStream(arr))
            {
                result = ProtoBuf.Serializer.Deserialize<testClass>(ms);
                ms.Close();
            }
            return result;
        }

        byte[] Ser(testClass t)
        {
            using (var ms = new System.IO.MemoryStream())
            {
                ProtoBuf.Serializer.Serialize(ms, t);
                return ms.ToArray();
            }
        }

    }
    [ProtoBuf.ProtoContract]
    public class testClass
    {
        [ProtoBuf.ProtoMember(1)]
        public string token { get; set; }

        [ProtoBuf.ProtoMember(2)]
        public double[] dat { get; set; }
        [ProtoBuf.ProtoMember(3)]

        public Dictionary<string, string> dic { get; set; }
    }


}
